package com.runjian.rundo.iot.agent.common.thread;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

import lombok.Getter;

/**
 * 线程工厂
 *
 * @author CaoQingHua
 */
@Getter
public class CommonThreadFactory implements ThreadFactory {

    private final AtomicInteger idx = new AtomicInteger(1);
    private static final Map<String, AtomicInteger> groupIndexMap = new ConcurrentHashMap<>();
    private final String threadGroupName;
    private final int groupIndex;

    public CommonThreadFactory(String threadGroupName) {
        this.threadGroupName = threadGroupName;
        AtomicInteger groupIdx = groupIndexMap.get(threadGroupName);
        if (groupIdx == null) {
            groupIdx = new AtomicInteger(0);
            groupIndexMap.put(threadGroupName, groupIdx);
        }
        this.groupIndex = groupIdx.getAndIncrement();

    }

    @Override
    public Thread newThread(Runnable r) {
        return new Thread(r, threadGroupName + "-" + groupIndex + "-Thread-" + idx.getAndIncrement());
    }
}
